package xiang.weiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import xiang.weiyu.common.R;
import xiang.weiyu.dto.DishDto;
import xiang.weiyu.pojo.Dish;
import xiang.weiyu.pojo.DishFlavor;
import xiang.weiyu.pojo.Setmeal;
import xiang.weiyu.pojo.SetmealDish;
import xiang.weiyu.service.DishFlavorService;
import xiang.weiyu.service.DishService;
import xiang.weiyu.service.SetmealDishService;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${reggie.path}")
    private String path;

    /**
     * 新增
     *
     * @param dishDto
     * @return R<String>
     */
    @PostMapping
    public R<String> insert(@RequestBody DishDto dishDto) {
        dishService.saveWithFlover(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 删除/批量删除
     *
     * @param ids
     * @return R<String>
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids) {
        //如果菜品已经和套餐关联,不允许删除
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
            qw.eq(SetmealDish::getDishId, id);
            List<SetmealDish> list = setmealDishService.list(qw);
            for (SetmealDish s : list) {
                if (s != null) {
                    return R.error("菜品已关联套餐,删除失败");
                }
            }
        }

        //删除存储的图片文件
/*        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            qw.eq(Dish::getId, id);
            Dish one = dishService.getOne(qw);
            //获取图片名称
            String image = one.getImage();
            //字节流删除本地图片文件
            File file = new File(path + image);
            if (file.exists()) {
                boolean delete = file.delete();
                log.info("图片文件是否删除: " + delete);
            }
        }*/

        //未关联，允许删除
        dishService.removeByIds(ids);
        return R.success("菜品删除成功");
    }

    /**
     * 修改
     *
     * @param dishDto
     * @return R<String>
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateDish(dishDto);

        //清理某个分类下的菜品缓存数据,保证更新时的数据一致性
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("菜品修改成功");
    }

    /**
     * (数据回显)修改
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByDishId(id);
        return R.success(dishDto);
    }

    /**
     * 批量修改 销售状态
     *
     * @param status
     * @param ids
     * @return R<String>
     */
    @PostMapping("/status/{status}")
    public R<String> statusDish(@PathVariable Integer status, @RequestParam List<Long> ids) {
        //如果菜品已经和套餐关联,不允许修改
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
            qw.eq(SetmealDish::getDishId, id);
            List<SetmealDish> list = setmealDishService.list(qw);
            for (SetmealDish s : list) {
                if (s != null) {
                    return R.error("该菜品已关联套餐,无法修改销售状态");
                }
            }
        }

        //批量修改状态,停售
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus, status).in(Dish::getId, ids);
        dishService.update(qw);
        //批量修改状态,起售
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("菜品状态修改成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return R<Page>
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //条件查询,当name不为空时才进行
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //根据字段(sort)进行排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //调用业务层进行分页查询
        dishService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 查询 菜品分类内的菜品
     *
     * @param dish
     * @return R<List < Dish>>
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        //自定的一个redis key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断redis中有没有缓存
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //根据categoryId/套餐id查询关联的菜品,值不为空并且 状态为1/起售状态
        qw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        qw.eq(Dish::getStatus, 1);
        //排序
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(qw);
        dishDtoList = list.stream().map(dishs -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dishs, dto);
            LambdaQueryWrapper<DishFlavor> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(DishFlavor::getDishId, dishs.getId());
            List<DishFlavor> list2 = dishFlavorService.list(qw2);
            dto.setFlavors(list2);
            return dto;
        }).collect(Collectors.toList());

        //redis中不存在相关缓存数据,存入redis,60分钟的存在时间
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}